package com.sinodata.bsm.center.engine.event.worker;

import org.apache.log4j.Logger;

import com.sinodata.bsm.center.cache.NewEventCache;
import com.sinodata.bsm.center.engine.event.EventWorker;
import com.sinodata.bsm.center.service.event.EventService;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.vo.Event;

/**
 * 
 * <p>
 * Description: 事件处理工作流：事件保存
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-29 AM 10:17:41    liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class EventSaveWorker implements EventWorker {

    private static final Logger logger = Logger.getLogger("event");

    private final static int MAX_MSG_LENGTH = 500;

    private final EventService eventService = SpringContextHolder.getBean(EventService.class);

    private final NewEventCache newEventCache = SpringContextHolder.getBean(NewEventCache.class);

    public EventSaveWorker() {

    }

    @Override
    public void execute(Event event) {
        String msg = event.getMsg();
        if (msg != null && msg.getBytes().length > MAX_MSG_LENGTH) {
            logger.info("Event message length is too long:" + msg);
            byte[] bytes = new byte[MAX_MSG_LENGTH];
            System.arraycopy(msg.getBytes(), 0, bytes, 0, MAX_MSG_LENGTH);
            msg = new String(bytes);
            event.setMsg(msg + "(was cut off)");
        }
        //设置事件更新次数
        if (event.getCount() == null || event.getCount() <= 0) {
            event.setCount(1);
        }
        if (event.getLastOccurTime() == null) {
            event.setLastOccurTime(event.getOccurTime());
        }
        try {
            eventService.add(event);
            logger.info("[SAVE]\t" + event.toString());
        } catch (Exception e) {
            logger.error("", e);
            return;
        }
        //恢复事件、正常事件不放入新事件缓存中,清除事件也不放入
        if (event.getCatalog() != EventConstants.CATALOG_REFAULTEVENT && event.getCatalog() != EventConstants.CATALOG_RULE_CLEAR && event.getLevel() != EventConstants.LEVEL_NORMAL && event.getLevel() != EventConstants.LEVEL_NO) {
            newEventCache.put(event.getId(), event);
        }
    }
}
